<!--
* description: 盘点单制作
* author: xuliwen
* createdDate: 2021-01-21
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="false"
      :dynamic-is-init-table="true"
      :dynamic-is-show-more-btn="true"
      :dynamic-api-style="'restful'"
      :callback-obj="callbackObj"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :dynamic-api-style="'restful'"
      @close="close"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/pa/apiBranchWarehouse'
import request from '@/utils/request'
import Vue from 'vue'
import { exportExcel } from '@/utils/getTimeString.js'

export default {
  name: 'InventoryMaking',

  components: {
    OneTableTemplate,
    Edit: () => import('./inventoryAdd.vue')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      icon: 'el-icon-arrow-down',
      status: false,
      editRowData: {},
      selectiondata: null,
      // 网格查询API配置对象
      apiConfig: api.queryCheckStoreMakeInfo,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.resets(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          name: 'add',
          disabled: false,
          clickEvent: this.add,
          text: '开始盘点', // 新增
          position: 'left'
        },
        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          name: 'adopt',
          clickEvent: () => this.pass('1'),
          text: '实绩提交', // 实绩提交
          position: 'left'
        },
        {
          compKey: 'btnKey5',
          type: '',
          size: 'small',
          name: 'adopt',
          clickEvent: () => this.pass('2'),
          text: '结束盘点', // 结束盘点
          position: 'left'
        },
        {
          compKey: 'btnKey6',
          type: '',
          size: 'small',
          name: 'reject',
          clickEvent: () => this.pass('0'),
          text: '删除盘点单', // 删除盘点单
          position: 'left'
        },
        {
          compKey: 'btnKey8',
          type: 'text',
          size: 'small',
          name: '',
          position: 'upload',
          click: (event) => {
            this.templateDownload()
          }
        },
        {
          compKey: 'btnKey7',
          type: '',
          size: 'small',
          name: 'importTemplate',
          position: 'upload',
          clickEvent: () => this.handFileListChange(),
          text: '实绩导入'
        },
        {
          compKey: 'btnKey9',
          type: '',
          size: 'small',
          clickEvent: () => this.exportExcel111(),
          text: '导出',
          name: 'export',
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '盘点单号：',
              codeField: 'checkStoreCode',
              disabled: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '盘点方式：',
              disabled: true,
              codeField: 'checkModel',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '2', statusText: '抽盘' },
                { statusId: '1', statusText: '全盘' }
              ],
              clearable: false,
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '盘点状态：',
              codeField: 'storeCheckStatus',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '开始盘点' },
                { statusId: '2', statusText: '财务驳回' },
                { statusId: '3', statusText: '盘点审核' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '盘点人：',
              codeField: 'checker',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '盘点开始时间：',
              codeField: 'beginDate',
              disabled: true,
              component: () =>
                import('@/components/org/datePicker/dateTimePick'),
              format: 'yyyy-MM-dd HH:mm:ss',
              dateType: 'datetime',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey6',
              labelName: '盘点结束时间：',
              codeField: 'endDate',
              disabled: true,
              component: () =>
                import('@/components/org/datePicker/dateTimePick'),
              format: 'yyyy-MM-dd HH:mm:ss',
              dateType: 'datetime',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey7',
              labelName: '过滤条件：',
              codeField: 'filtration',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '只显示相符' },
                { statusId: '2', statusText: '只显示盘盈' },
                { statusId: '3', statusText: '只显示盘亏' },
                { statusId: '4', statusText: '只显示差异' },
                { statusId: '5', statusText: '只显示有物无账' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey8',
              labelName: '只显示未提交实际的备件',
              codeField: 'noSubmitPart',
              // lookuptype: "VE0212",
              component: () => import('@/components/org/checkBox'),
              type: 'inputText',
              isMul: false,
              isMust: false,
              span: 8
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partId',
              label: '备件ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partNo',
              label: '备件编码'
            },
            {
              prop: 'partName',
              label: '备件名称'
            },
            {
              prop: 'warehouseName',
              label: '仓库名称',
              width: '150px'
            },
            {
              prop: 'placeId',
              label: '仓位编码',
              width: '100px'
            },
            {
              prop: 'storageQty',
              label: '账面数量'
            },
            {
              prop: 'factQty',
              label: '盘点实数+',
              isComponent: true,
              comps: [
                {
                  compKey: 'compKey5' + this.$utils.generateId(),
                  codeField: 'factQty',
                  component: () =>
                    import('@/components/org/commonInput/numberInput.vue'),
                  // isInput: true,
                  dataToObject: {
                    min: 0,
                    empty: true
                  },
                  decPoint: 0,
                  step: 1
                }
              ]
            },
            {
              prop: 'checker',
              label: '盘点人+',
              isComponent: true,
              comps: [
                {
                  compKey: 'compKey5' + this.$utils.generateId(),
                  codeField: 'checker',
                  component: () => import('@/components/org/commonInput'),
                  isInput: true,
                  dataToObject: {
                    empty: true
                  },
                  type: 'inputText'
                }
              ]
            },
            {
              prop: 'profitQty',
              label: '盈亏数量'
            },
            {
              prop: 'isEditCn',
              label: '是否已录入盘点实数',
              width: '100px'
            },
            {
              prop: 'lastEditDate',
              label: '盘点实数导入时间',
              width: '150px'
            },
            {
              prop: 'unit',
              label: '计量单位'
            },
            {
              prop: 'remark',
              label: '盈亏原因+',
              isComponent: true,
              comps: [
                {
                  compKey: 'compKey5' + this.$utils.generateId(),
                  codeField: 'remark',
                  component: () => import('@/components/org/commonInput'),
                  type: 'inputText'
                }
              ]
            }
          ],
      callbackObj: {
        // 查询成功后回调
        onQueryReturn: (response) => {
          this.onQueryReturn(response)
        }
      },
      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          checkStoreCode: '',
          checkModel: '',
          storeCheckStatus: '',
          checker: '',
          beginDate: '',
          endDate: '',
          filtration: '',
          noSubmitPart: '0'
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      )
    }
  },
  watch: {
    'formField.orderStatus': {
      deep: true,
      handler: function(newV, oldV) {
        console.log('watch中：', newV)
        // this.querybystatus(newV)
        this.queryTable()
      }
    }
  },
  mounted() {
    // 列表查询
    this.queryTable(1)
  },
  methods: {
    resets() {
      for (const attr in this.formField) {
        if (!['checkModel', 'checkStoreCode', 'beginDate', 'endDate'].includes(attr)) {
          this.formField[attr] = ''
        }
      }
    },
    onQueryReturn(res) {
      if (res.rows.length > 0 && res.rows) {
        this.formField.checkStoreCode = res.rows[0].checkStoreCode
        this.formField.checkModel = res.rows[0].checkModel
        this.formField.beginDate = res.rows[0].beginDate
        this.formField.endDate = res.rows[0].endDate
        this.tableButtons[2].disabled = true
      } else {
        this.formField.checkStoreCode = ''
        this.formField.checkModel = ''
        this.formField.beginDate = ''
        this.formField.endDate = ''
        this.tableButtons[2].disabled = false
      }
    },
    async pass(type) {
      const parmaList = this.$refs['multipleTable'].list
      let urlApi = ''
      let isValid = true
      parmaList.every(row => {
        if (!row['factQty'] || !row['checker']) {
          isValid = false
          return false
        }
        return true
      })
      if (!isValid && type == '1') {
        return this.$message('网格中[ 盘点实数+ ] [ 盘点人+ ] 为必填项！')
      }
      if (type == '1') {
        // 实绩提交
        urlApi = api.submitCheckStore.APIUrl
      } else if (type == '2') {
        // 结束盘点
        urlApi = api.endCheckStore.APIUrl
      } else if (type == '0') {
        // 删除盘点单
        const res = await this.$confirm('确定要删除盘点单吗？')
        if (res !== 'confirm') return
        urlApi = api.deleteCheckStore.APIUrl
      }
      request({
        url: urlApi,
        method: 'post',
        data: parmaList
      }).then((res) => {
        this.$message.success(res.msg)
        this.queryTable(1)
      })
    },
    exportExcel111() {
      exportExcel(
        this.formField,
        api.exportCheckStoreDetails.APIUrl,
        api.exportCheckStoreDetails.ServiceCode,
        '盘点单制作导出'
      )
    },
    templateDownload() {
      const fileName = this.$utils.fileNameWithTime('盘点单制作.xlsx')
      this.$requestAPI({
        apiUrl: api.downloadTemplateToCheckStore.APIUrl,
        variables: { dataType: 'excel' }
      })
        .then((res) => {
          this.$utils.downloadFile(res, fileName)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType != 'xls' && fileType != 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      const that = this
      const url = api.importExcelToCheckStore.APIUrl
      that
        .$requestUpload(url, param)
        .then((response) => {
          loading.close()
          if (response.result === '1') {
            this.$message.success(response.msg)
            this.queryTable(1)
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
        .catch((err) => {})
        .finally(() => {
          loading.close()
        })
    },
    // 编辑获取数据
    edit(index) {
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
      this.editRowData = this.$utils.deepCopy(
        this.$refs['multipleTable'].list[index]
      )
    }
  }
}
</script>
<style lang='scss' scoped>
.red {
  background: red;
}
</style>
